from django.db import models
from django.core import serializers

import urllib2_file
import urllib2

from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder
python_serializer = serializers.get_serializer("python")()

def prep_objects(queryset, model=None, username=None, password=None, include_pk=True, action='add'):
    post_data = dict()
    data = python_serializer.serialize(queryset)
    files = list()
    if not model:
        model = queryset.model
    for field in model._meta.fields:
        if isinstance(field, models.FileField):
            files.append(field.name)
    index = 0
    for object in queryset:
        for name in files:
            data_name = 'file_%s_%s' % (index, name)
            try:
                post_data[data_name] = getattr(object, name).file
            except ValueError:
                pass
            except IOError:
                data[index]['fields'][name] = ''
            else:
                data[index]['fields'][name] = data_name
        data[index]['action'] = action
        if not include_pk:
            del data[index]['pk']
        index += 1
    post_data['json'] = simplejson.dumps(data, cls=DjangoJSONEncoder)
    if username and password:
        post_data['username'] = username
        post_data['password'] = password
    return post_data

def send_objects(url, queryset, model=None, username=None, password=None, include_pk=True, action='add'):
    return urllib2.urlopen(url, prep_objects(queryset, model, username, password, include_pk, action))
